<template>
  <a-modal
    v-model:visible="visible"
    modal-class="modal-form-large"
    title-align="start"
    :title="title"
    :top="30"
    :align-center="false"
    :draggable="true"
    :mask-closable="false"
    :unmount-on-close="true"
    :ok-button-props="{ disabled: loading }"
    :cancel-button-props="{ disabled: loading }"
    :on-before-ok="handlerOk"
    @close="handleClose"
  >
    <a-spin class="form-full" :loading="loading">
      <a-form
        ref="formRef"
        :model="formModel"
        label-align="right"
        :auto-label-width="true"
        :rules="formRules"
      >
        <!-- 上级菜单 -->
        <a-form-item field="pid" label="上级菜单">
          <menu-tree-selector
            v-model:model-value="formModel.pid as number"
            :disabled="false"
          />
        </a-form-item>
        <!-- 菜单名称 -->
        <a-form-item field="title" label="菜单名称">
          <a-input v-model="formModel.title" placeholder="请输入菜单名称" />
        </a-form-item>
        <!-- 菜单类型 -->
        <a-form-item v-if="isAddHandle" field="type" label="菜单类型">
          <a-radio-group v-model="formModel.type" type="button">
            <a-radio :value="1">目录</a-radio>
            <a-radio :value="2">菜单</a-radio>
            <a-radio :value="3">按钮</a-radio>
          </a-radio-group>
        </a-form-item>
        <!-- 菜单图标 -->
        <a-form-item v-if="formModel.type < 3  " field="icon" label="菜单图标">
          <icon-picker v-model:icon="formModel.icon as string">
            <template #iconSelect>
              <a-input v-model="formModel.icon" placeholder="请选择菜单图标" />
            </template>
          </icon-picker>
        </a-form-item>
        <!-- 菜单权限 -->
        <a-form-item
          v-if="formModel.type ===3"
          field="permission"
          label="按钮权限"
        >
          <a-input
            v-model="formModel.permission"
            placeholder="按钮权限 sys:system-menu:query"
            allow-clear
          />
        </a-form-item>
        <!-- 组件名称 -->
        <a-form-item
          v-if="formModel.type !== 3"
          field="component"
          label="组件名称"
        >
          <a-input
            v-model="formModel.component"
            placeholder="请输入路由组件名称"
            allow-clear
          />
        </a-form-item>
        <!-- 路由地址 -->
        <a-form-item

          field="path"
          label="路由地址"
          tooltip="输入组件名称后则不会生效"
        >
          <a-input
            v-model="formModel.path"
            placeholder="请输入路由地址"
            allow-clear
          />
        </a-form-item>
        <!-- 菜单排序 -->
        <a-form-item field="sort" label="菜单排序">
          <a-input-number
            v-model="formModel.sort"
            placeholder="排序"
            :style="{ width: '120px' }"
            allow-clear
            hide-button
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import useLoading from '@/hooks/loading';
  import useVisible from '@/hooks/visible';
  import type { UpdateRequest } from '@/api/system/menu';
  import IconPicker from '@sanqi377/arco-vue-icon-picker';
  import MenuTreeSelector from '@/components/system/menu/tree-selector/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { updateRows } from '@/api/system/menu';
  import formRules from '../types/form.rules';
  import { getList ,type QueryRequest,QueryResponse } from '@/api/system/menu';
  import { useCacheStore } from '@/store';

  const { visible, setVisible } = useVisible();
  const { loading, setLoading } = useLoading();
  const title = ref<string>();
  const isAddHandle = ref<boolean>(true);
  const cacheStore = useCacheStore();

  const defaultForm = (): UpdateRequest => {
    return {
      id: undefined,
      pid: 0,
      title: undefined,
      type: undefined,
      permission: undefined,
      sort: undefined,
      target: undefined,
      icon: undefined,
      path: undefined,
      component: undefined,
    };
  };
  const formRef = ref();
  const formModel = ref<UpdateRequest>({});
  const emits = defineEmits(['restart']);

  const renderForm = (record: any) => {
    formModel.value = { ...record };
  };
  const openAdd = (record: any) => {
    title.value = '添加菜单';
    isAddHandle.value = true;
    renderForm({
      ...defaultForm(),
      pid: record.pid,
      sort: (record.sort || 0) + 10,
    });
    setVisible(true);
  };
  // 打开修改
  const openUpdate = (record: any) => {
    title.value = '修改菜单';
    isAddHandle.value = false;

    renderForm({ ...defaultForm(), ...record });
    setVisible(true);
  };

  defineExpose({ openAdd, openUpdate });
  // 选择根目录 parentId 设置为 0
  watch(
    () => formModel.value.type,
    () => {
      if (formModel.value.type === 0 && formModel.value.pid === 0) {
        formModel.value.pid = 0;
      }
    }
  );

  // 清空
  const handlerClear = () => {
    setLoading(false);
    // 触发 watch 防止第二次加载变成根目录
    renderForm(defaultForm());
  };
  // eslint-disable-next-line consistent-return
  const handlerOk = async () => {
    setLoading(true);
    try {
      // 验证参数
      const error = await formRef.value.validate();
      if (error) {
        return false;
      }
      console.log(formModel.value)
      // 验证父菜单
      if (formModel.value.pid === 0 && formModel.value.type != 1) {
        formRef.value.setFields({
          pid: {
            status: 'error',
            message: '创建子目录或功能时 父菜单不能为根目录',
          },
        });
        return false;
      }
      await updateRows(formModel.value);
      if (isAddHandle.value) {
        // 新增
        Message.success('创建成功');
        //重载菜单
         loadMenuData(true)
      } else {
        // 修改
        Message.success('修改成功');
      }
      emits('restart');
      // 清空
      handlerClear();
    } catch (e) {
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 加载菜单
  const loadMenuData = async (all: any = undefined) => {
    try {
      const { data } = await getList([] as QueryRequest);
      // 重设缓存
      if (all) {
        cacheStore.set('menus', data);
      }
    } catch (e) {
    } finally {}
  };

  const handleClose = async () => {
    handlerClear();
  };
</script>

<style scoped lang="less"></style>
